<?php

namespace app\zyhsapi\controller\v1;

use app\aliyun\controller\AliyunFilterWord;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrMessage;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsAstrTasks;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsQuestionUserView;
use app\zyhsapi\model\ZyhsRecode;
use app\zyhsapi\model\ZyhsUserAccount;
use app\zyhsapi\model\ZyhsUserAddQuestion;
use app\zyhsapi\model\ZyhsUserQuestion;
use app\zyhsapi\model\ZyhsUserQuestionComment;
use app\zyhsmarketing\service\MarketingCallback;
use think\Log;
use think\response\Json;

class QuestionAnswer extends ZyhsAuth
{
    /**
     * 问答首页
     * @return Json
     * @throws \Exception
     */
    public function index()
    {
        $page = input('page/d', 1);
        if ($page < 1)
        {
            $page = 1;
        }
        $zyhsUserQuestionModel = new ZyhsUserQuestion();

        $testAccountConfig = (new ZyhsConfig())->configInfo('rtc');
        if (Util::ZyhsIsHuaweiOrHonorHg())
        {
            if (Util::IsHuawei())
            {
                $idList = $testAccountConfig['huawei_hg_ask_list_ids'] ? explode(',', $testAccountConfig['huawei_hg_ask_list_ids']) : [];
            } else
            {
                $idList = $testAccountConfig['honor_hg_ask_list_ids'] ? explode(',', $testAccountConfig['honor_hg_ask_list_ids']) : [];
            }
            $total = count($idList);
            $pageDataIds = [
                'total' => $total,// 记录总数
                'per_page' => $total,// 每页多少条
                'current_page' => $page,// 当前页数
                'last_page' => 1,// 总页数
                'data' => [],
            ];
            foreach ($idList as $idItem)
            {
                $pageDataIds['data'][$idItem] = $idItem;
            }
        } else
        {
            $pageDataIds = $zyhsUserQuestionModel->getQuestionTimeSortIds($page, 15);
        }
        if ($pageDataIds['data'])
        {
            $ids = array_keys($pageDataIds['data']);
            $questionData = $zyhsUserQuestionModel->batchGetInfoByIds($ids, ['id', 'uid', 'question', 'question_type', 'is_hide', 'extend']);
            $questionConfig = config('zyhs_question.question_type_title');
            $testUids = explode(',', $testAccountConfig['zyhsapp_test_user_id']);
            $resData = [];
            $astrInfoList = [];
            foreach ($pageDataIds['data'] as $key => $sort)
            {
                $questionItem = $questionData[$key] ?? null;
                if (!$questionItem || in_array($questionItem['uid'], $testUids, false) || (Util::IsHuaweiOrHonor() && $questionItem['question_type'] === 3))
                {   // 问题获取异常 或者 测试用户发送的问题隐藏
                    continue;
                }
                if ($questionItem && $questionItem['is_hide'] === 0)
                {
                    $receivingTasks = $questionItem['extend']['receiving_tasks'] ?? [];
                    $avatarList = [];
                    foreach ($receivingTasks as $receivingTaskItem)
                    {
                        if (isset($receivingTaskItem['is_reply']) && $receivingTaskItem['is_reply'])
                        {
                            if (!isset($astrInfoList[$receivingTaskItem['astr_id']]))
                            {
                                $astrInfoItem = (new ZlcrAstr())->getInfoById($receivingTaskItem['astr_id'], ['avatar']);

                                $astrInfoList[$receivingTaskItem['astr_id']] = $astrInfoItem['avatar'] ?? '';
                            }
                            $avatarList[] = $astrInfoList[$receivingTaskItem['astr_id']];
                        }
                    }
                    $replyNum = count($avatarList);
                    if ($replyNum > 0)
                    {
                        $des = $replyNum . '名咨询师已回复';
                    } else
                    {
                        $des = '暂无回复';
                    }
                    $resData[] = [
                        'id' => $questionItem['id'],
                        'question' => $questionItem['question'],
                        'avatar_list' => $avatarList,
                        'des' => $des,
                        'question_type' => $questionItem['question_type'],
                        'qt_icon' => $questionConfig[$questionItem['question_type']]['icon'] ?? '',
                        'qt_name' => $questionConfig[$questionItem['question_type']]['name'] ?? '',
                    ];
                }
            }
            $pageDataIds['data'] = $resData;
        }

        $unReadIds = $this->user ? $zyhsUserQuestionModel->getUserUnReadIds($this->user['id']) : [];
        $pageDataIds['is_new'] = count($unReadIds) > 0 ? 1 : 0;

        return show(config('code.success'), '请求成功', $pageDataIds);
    }

    /**
     * 我的提问
     * @return Json
     * @throws \Exception
     */
    public function getMyQuestions()
    {
        $zyhsUserQuestionModel = new ZyhsUserQuestion();
        $pageData = $zyhsUserQuestionModel->getListPage($this->user['id'], 'create_time', ['id', 'question', 'create_time', 'is_read', 'order_num', 'question_type', 'extend']);
        $pageData['data'] = $zyhsUserQuestionModel->dataInit($pageData['data']);
        $questionConfig = config('zyhs_question.question_type_title');

        $resData = [];
        foreach ($pageData['data'] as $dataItem)
        {
            $receivingTasks = $dataItem['extend']['receiving_tasks'] ?? [];
            $receivingNum = count($receivingTasks);
            if ($receivingNum)
            {
                $replyNum = 0;
                foreach ($receivingTasks as $receivingTask)
                {
                    if (isset($receivingTask['is_reply']) && $receivingTask['is_reply'])
                    {
                        $replyNum++;
                    }
                }
                $desc = $receivingNum . '名咨询师接单';
                if ($replyNum > 0)
                {
                    $desc .= "/{$replyNum}名咨询师已回复";
                }
            } else
            {
                $desc = '暂无咨询师接单';
            }
            $resData[] = [
                'id' => $dataItem['id'],
                'question' => $dataItem['question'],
                'create_time' => date('Y-m-d H:i:s', $dataItem['create_time']),
                'question_type' => $dataItem['question_type'],
                'qt_icon' => $questionConfig[$dataItem['question_type']]['icon'] ?? '',
                'qt_name' => $questionConfig[$dataItem['question_type']]['name'] ?? '',
                'des' => $desc,
                'is_new' => $dataItem['is_read'] === 0 ? 1 : 0,
                'order_num' => $dataItem['order_num'],
            ];
        }
        $pageData['data'] = $resData;

        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 问答问题详情
     * @return Json
     */
    public function questionDetail()
    {
        $qid = input('qid/s', '');
        if (!$qid)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsQuestionModel = new ZyhsUserQuestion();
        $zyhsAstrTasksModel = new ZyhsAstrTasks();
        $consultModel = new Zlcr3ConsultAccount();
        $zlcrAstrModel = new ZlcrAstr();
        $zyhsUserAddQuestionModel = new ZyhsUserAddQuestion();
        $zyhsQuestionUserViewModel = new ZyhsQuestionUserView();
        $zyhsUserQuestionCommentModel = new ZyhsUserQuestionComment();

        $questionInfo = $zyhsQuestionModel->getInfoById($qid, ['id', 'question', 'uid', 'question_type', 'question_extend', 'extend', 'create_time', 'gid', 'status', 'is_read', 'consult_num', 'receiving_num']);
        if ($questionInfo['is_read'] === 0)
        {
            $zyhsQuestionModel->UpdateData($qid, ['is_read' => 1, 'uid' => $questionInfo['uid'], 'update_time' => $this->request->time()]);
        }
        $questionConfig = config('zyhs_question');
        $goodConfig = config('zyhsgoods.qa_goods');
        $isSelf = $this->user && $questionInfo['uid'] === $this->user['id'];
        // 用户蹭看的 咨询师任务ID
        $userViewData = [];
        if (!$isSelf && $this->user)   // 获取 用户蹭看的任务信息
        {   // 不是自己查看 并且 已登陆
            $userViewData = $zyhsQuestionUserViewModel->getUserViewQuestionTaskIds($this->user['id']);
        }
        $questionData = [
            'astro_data' => [],
            'dice_data' => null,
            'tarot_data' => null,
        ];
        switch ($questionInfo['question_type'])
        {
            case 1:
                if ($isSelf)
                {
                    $zyhsRecodeModel = new ZyhsRecode();
                    if (isset($questionInfo['question_extend']['recode1']) && $questionInfo['question_extend']['recode1'])
                    {
                        $recodeInfo1 = $zyhsRecodeModel->getInfoById($questionInfo['question_extend']['recode1']['id']);
                        if (!$recodeInfo1 || $recodeInfo1['status'] !== 1)
                        {   // 是否 已删除
                            $recodeStatus = 2; // 已删除
                            $toast = '档案已删除，不支持查看';
                        } else
                        {   // 是否 已更新
                            $isModify = $zyhsQuestionModel->recodeModifyCheck($questionInfo['question_extend']['recode1'], $recodeInfo1);
                            if ($isModify)
                            {
                                $toast = '档案已发生变更，不支持查看';
                                $recodeStatus = 1;
                            } else
                            {
                                $toast = '';
                                $recodeStatus = 0;
                            }
                        }
                        $questionData['astro_data'][] = [
                            'nickname' => $questionInfo['question_extend']['recode1']['name'],
                            'avatar' => $questionInfo['question_extend']['recode1']['avatar'],
                            'status' => $recodeStatus,
                            'toast' => $toast,
                            'rid' => $questionInfo['question_extend']['recode1']['id'],
                        ];
                    }
                    if (isset($questionInfo['question_extend']['recode2']) && $questionInfo['question_extend']['recode2'])
                    {
                        $recodeInfo2 = $zyhsRecodeModel->getInfoById($questionInfo['question_extend']['recode2']['id']);
                        if (!$recodeInfo2 || $recodeInfo2['status'] !== 1)
                        {   // 是否 已删除
                            $recodeStatus = 2; // 已删除
                            $toast = '档案已删除，不支持查看';
                        } else
                        {   // 是否 已更新
                            $isModify = $zyhsQuestionModel->recodeModifyCheck($questionInfo['question_extend']['recode2'], $recodeInfo2);
                            if ($isModify)
                            {
                                $toast = '档案已发生变更，不支持查看';
                                $recodeStatus = 1;
                            } else
                            {
                                $toast = '';
                                $recodeStatus = 0;
                            }
                        }
                        $questionData['astro_data'][] = [
                            'nickname' => $questionInfo['question_extend']['recode2']['name'],
                            'avatar' => $questionInfo['question_extend']['recode2']['avatar'],
                            'status' => $recodeStatus,
                            'toast' => $toast,
                            'rid' => $questionInfo['question_extend']['recode2']['id'],
                        ];
                    }
                }
                break;
            case 2:
                $questionData['dice_data'] = $questionInfo['question_extend']['dice_data'] ?? null;
                break;
            case 3:
                $questionData['tarot_data'] = $questionInfo['question_extend']['tarot_data'] ?? null;
                break;
            default:
        }

        // 取 咨询师 回复答案信息
        $answerData = [];
        $receivingTasks = $questionInfo['extend']['receiving_tasks'] ?? [];
        $complainText = [
            -1 => '',
            0 => '',
            1 => '你已提交申诉请耐心等待结果…',
            2 => '申诉成功已退款',
            3 => '未发现你所申诉的相关问题，',
        ];
        // 是否 关闭申述状态
        $isCloseComplainStatus = $this->request->time() - $questionInfo['create_time'] > 460800;    // 8小时 + 48小时 +72小时(3天) = 460800
        foreach ($receivingTasks as $receivingTaskItem)
        {
            $evaluationData = null;
            if (isset($receivingTaskItem['is_reply']) && $receivingTaskItem['is_reply'] === 1)
            {   // 占星师 已回复
                $taskId = $receivingTaskItem['task_id'];
                $taskInfo = $zyhsAstrTasksModel->getInfoById($taskId, ['astr_id', 'is_comment', 'status', 'reply_time', 'answer_content', 'answer_duration', 'complain_status', 'success_time']);
                // 获取占星师信息
                $astrInfo = $zlcrAstrModel->getInfoById($taskInfo['astr_id'], ['nickname', 'avatar']);
                // 获取咨询师信息
                $consultInfo = $consultModel->getInfoById($taskInfo['astr_id'], ['level', 'status', 'tids', 'tags']);

                if ($taskInfo['is_comment'] === 1)
                {   //  已评价
                    $evaluationData = $zyhsUserQuestionCommentModel->getCommentData($taskId);
                }
                // 获取追问信息
                $superadditionList = [];
                $answerIsShow = false; // 答案是否展示
                if ($isSelf || in_array($taskId, $userViewData, true))
                {   // 如果已蹭看 或者是发布自己的问题
                    $answerIsShow = true;
                    $lookGoodData = null;
                } else
                {
                    $lookGoodData = $zyhsQuestionUserViewModel->getLookGoodData();
                }
                if ($answerIsShow)
                {
                    $addQuestionStatus = [
                        2 => 1,
                        4 => 1,
                        5 => 2,
                        6 => 3,
                        7 => 3,
                        8 => 3,
                    ];
                    $addQuestionData = $zyhsUserAddQuestionModel->getQuestionAddQuestionInfo($taskId);
                    foreach ($addQuestionData as $addQuestionItem)
                    {
                        if (!$isSelf && $addQuestionItem['status'] !== 4)
                        {
                            continue;
                        }
                        $status = $addQuestionStatus[$addQuestionItem['status']];
                        $tips = '';
                        if ($status === 2)
                        {
                            $tips = '追问已取消，取消原因：' . $addQuestionItem['cannel_tag_name'];
                        } elseif ($status === 3)
                        {
                            switch ($addQuestionItem['status'])
                            {
                                case 7:
                                case 8:
                                    $tips = '因申诉受理，追问已自动取消';
                                    break;
                                default:
                                    $tips = '占星师回复超时，追问已取消';
                            }
                        }
                        $addQuestionAnswerData = null;
                        if ($addQuestionItem['status'] === 4)
                        {
                            $addQuestionAnswerData = [
                                'content' => $addQuestionItem['answer_content'],
                                'duration' => $addQuestionItem['answer_duration'],
                                'create_time' => Util::timeToStr($addQuestionItem['reply_time']),
                            ];
                        }
                        $superadditionList[] = [
                            'question_data' => [
                                'content' => $addQuestionItem['question'],
                                'create_time' => Util::timeToStr($addQuestionItem['create_time']),
                                'tips' => $tips,
                                'status' => $status,    //追问状态 1=>正常 2=>追问违规 3=>占星师回复超时
                            ],
                            'answer_data' => $addQuestionAnswerData,
                        ];
                    }
                }

                $btnData = [
                    [
                        'type' => 1,
                        'name' => '向Ta咨询',
                        'coin' => 0,
                    ],
                ];
                if ($isSelf && $taskInfo['status'] === 3 && $this->request->time() - $taskInfo['reply_time'] < 48 * 3600 && $taskInfo['complain_status'] === 0)
                {   // 自己的提问 并且状态为带追问状态 且在回答后48小时以内
                    $lastTime = 48 * 3600 - ($this->request->time() - $taskInfo['reply_time']);
                    $lastTime = Sec2Time2($lastTime);
                    // 获取追问商品ID
                    $addQuestionGid = $questionConfig['add_question'][$questionInfo['gid']];
                    // 获取追问价格
                    $price = $goodConfig[$addQuestionGid]['now_prize'];

                    $btnData[] = [
                        'type' => 2,    // 追问
                        'name' => "追问时间还剩{$lastTime}钟",
                        'coin' => $price,
                        'gid' => $addQuestionGid,
                    ];
                }

                if (in_array($taskInfo['status'], [6, 9, 10], true) && $taskInfo['complain_status'] === 0 && $isCloseComplainStatus)
                {   // 问答任务 已完成 且未申诉 且已超过3天
                    $taskInfo['complain_status'] = -1;
                }

                $answerData[] = [
                    'task_id' => $taskId,
                    'astr_id' => $taskInfo['astr_id'],
                    'nickname' => $astrInfo['nickname'],
                    'avatar' => $astrInfo['avatar'],
                    'status' => $consultInfo['status'], // 咨询师状态【1=>在线  2=>不在线】
                    'look_good_data' => $lookGoodData ?? null,
                    'level' => $consultInfo['level'] ?? 1,  // 咨询师 等级
                    'tags_icon' => $consultModel->getTagsIcon($consultInfo['tids']),
                    'tags' => $consultModel->getTags($consultInfo['tags']),
                    'content' => $answerIsShow ? $taskInfo['answer_content'] : '',
                    'duration' => $answerIsShow ? $taskInfo['answer_duration'] : 0,
                    'evaluation_status' => $taskInfo['is_comment'] > 0 ? 1 : 0,  // 0=>未评价, 1=>已评价 (评价状态)
                    'complaint_status' => $taskInfo['complain_status'],   // 0=>未申诉, 1=> 申诉中,2=>申诉成功, 3=> 申诉失败
                    'complaint_text' => $complainText[$taskInfo['complain_status']],     // 当前申诉状态的文案
                    'evaluation_data' => $evaluationData ?? null,    // 评价信息 ｜ null
                    'superaddition_list' => $superadditionList, // 追问列表
                    'btn_data' => $btnData,   // 按钮信息
                    'create_time' => Util::timeToStr($taskInfo['reply_time']),
                ];
            }
        }

        if ($this->user)
        {
            $zyhsUserAccountModel = new ZyhsUserAccount();
            $user_coin = $zyhsUserAccountModel->getUserCoinFromCache($this->user['id']);  // 账户信息
            $coinNum = (int)($user_coin['balance'] ?? 0); // 准币余额
        } else
        {
            $coinNum = 0;
        }
        $emptyAnswerTip = '';
        if (empty($answerData) && $questionInfo['status'] !== 3)
        {
            $emptyAnswerTip = '暂无回复请耐心等待';
        }

        $tip = '';
        if ($isSelf && isset($questionInfo['extend']['refund_data']))
        {
            $refundData = [1 => 0, 2 => 0];
            $n = 0;
            foreach ($questionInfo['extend']['refund_data'] as $refundItem)
            {
                if ($refundItem['type'] === 1)
                {
                    $refundData[1] = $refundData[1] + $refundItem['refund_amount'];
                } else
                {
                    $n++;
                    $refundData[2] = $refundData[2] + $refundItem['refund_amount'];
                }
            }
            if ($refundData[1] > 0)
            {
                if ($questionInfo['receiving_num'] === 0)
                {
                    $tip = "因暂无咨询师接单，已退款{$refundData[1]}币。";
                } else
                {
                    $i = $questionInfo['consult_num'] - $questionInfo['receiving_num'];
                    $tip = "因{$i}名咨询师接单，已退款{$refundData[1]}币。";
                }
            }
            if ($refundData[2] > 0)
            {
                if ($tip)
                {
                    $tip .= "\r\n";
                }
                $tip .= "因{$n}名咨询师被申诉成立，已退款{$refundData[2]}币。";
            }
        }
        $resData = [
            'isself' => $isSelf ? 1 : 0,
            'question_info' => [
                'qt_icon' => $questionConfig['question_type_title'][$questionInfo['question_type']]['icon'],
                'qt_name' => $questionConfig['question_type_title'][$questionInfo['question_type']]['name'],
                'question_type' => $questionInfo['question_type'],
                'create_time' => date('Y-m-d H:i:s', $questionInfo['create_time']),
                'question' => $questionInfo['question'],
                'question_data' => $questionData,
                'consult_num' => $questionInfo['consult_num'],  // 打点添加 咨询人数
                'question_status' => $questionInfo['status'] === 3 ? 2 : 1,  // 打点添加 1=>进行中 2=>已完成
            ],
            'answer_data' => $answerData,
            'tip' => $tip,
            'user_coin' => $coinNum,   // 用户当前准币余额
            'empty_answer_tip' => $emptyAnswerTip,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 发布问题介绍
     * @return Json
     */
    public function getAskQuestionIntro()
    {
        $user_coin = (new ZyhsUserAccount())->getUserCoinFromCache($this->user['id']);  // 账户信息
        $coinNum = (int)($user_coin['balance'] ?? 0); // 准币余额
        $questionConfig = config('zyhs_question');

        $dataList = [
            [
                'question_type' => 1,   // 1=>星盘 2=>骰子 3=>幸运卡牌
                'qt_icon' => $questionConfig['question_type_title'][1]['icon'],
                'qt_name' => $questionConfig['question_type_title'][1]['name'],
                'tip' => '什么类型的问题适合使用星盘解答？',
                'good_info' => [
                    10000,
                    10001,
                    10002,
                ],
            ],
        ];

        if (!Util::IsHuaweiOrHonor())
        {
            $dataList[] = [
                'question_type' => 3,   // 1=>星盘 2=>骰子 3=>幸运卡牌
                'qt_icon' => $questionConfig['question_type_title'][3]['icon'],
                'qt_name' => $questionConfig['question_type_title'][3]['name'],
                'tip' => '什么类型的问题适合使用幸运卡牌解答？',
                'good_info' => [
                    10003,
                    10004,
                    10005,
                ],
            ];
        }

        $dataList[] = [
            'question_type' => 2,   // 1=>星盘 2=>骰子 3=>幸运卡牌
            'qt_icon' => $questionConfig['question_type_title'][2]['icon'],
            'qt_name' => $questionConfig['question_type_title'][2]['name'],
            'tip' => '什么类型的问题适合使用骰子解答？',
            'good_info' => [
                10006,
                10007,
                10008,
            ],
        ];

        $resData = [
            'coin' => $coinNum,
            'data_list' => $dataList,
        ];

        $qaGoodConfig = config('zyhsgoods.qa_goods');

        foreach ($resData['data_list'] as $k => $datum)
        {
            $goodInfo = [];
            foreach ($datum['good_info'] as $gid)
            {
                if ($qaGoodConfig[$gid]['or_prize'] > $qaGoodConfig[$gid]['now_prize'])
                {
                    $oldPrice = $qaGoodConfig[$gid]['or_prize'] . '币';
                }
                $goodInfo[] = [
                    'gid' => $gid,
                    'gname' => $questionConfig['info'][$gid]['gname'],
                    'old_price' => $oldPrice ?? '',
                    'price' => $qaGoodConfig[$gid]['now_prize'],
                    'des' => $questionConfig['info'][$gid]['desc'],
                    'tip_icon' => $questionConfig['info'][$gid]['tip_icon'],
                ];
            }
            $resData['data_list'][$k]['good_info'] = $goodInfo;
        }

        if ($this->headers['channel'] === 'VIVO')
        {   // 已登陆 并且 是vivo
            $oaid = $this->headers['oaid'] ?? '';
            (new MarketingCallback())->uploadActiveData($oaid, $this->user['id'], 1, 3);
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 发布问题
     * @return Json
     * @throws \Exception
     */
    public function questionAdd()
    {
        $questionType = input('question_type/d', 0); // 1=>星盘问题,2=>骰子问题,3=>塔罗问题
        $question = input('question/s', '');
        $astroData = input('astro_data/s', '');
        $diceData = input('dice_data/s', '');
        $tarotData = input('tarot_data/s', '');

        if (!$question)
        {
            return show(config('code.error'), '请输入咨询问题');
        }

        if (mb_strlen($question) > 80)
        {
            return show(config('code.error'), '咨询问题最多80字');
        }

        if (!in_array($questionType, [1, 2, 3,], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if (Util::commentCheck($this->user['id'], [
            'action' => 'zyhsQuestionAdd',
            'question_type' => $questionType,
            'question' => $question,
            'astro_data' => $astroData,
            'dice_data' => $diceData,
            'tarot_data' => $tarotData,
        ]))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }

        $res = AliyunFilterWord::checkText($question, 'question_pic_check');
        //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
            //            return [
//                'status' => false,
//                'msg' => '问题中有敏感词'
//            ];
            return show(config('code.toast'), '问题中有敏感词');
        }

        $questionData = [
            'uid' => $this->user['id'],
            'question_type' => $questionType,
            'question' => $question,
        ];
        // 记录 占星师下单时的版本号
        $questionExtend = ['version' => $this->headers['version']];
        $isSynastry = 0; // 是否合盘
        switch ($questionType)
        {
            case 1: // 看盘
                $astroData = json_decode($astroData, true);
                if (!$astroData || !isset($astroData['rid1'], $astroData['astro_type']) || !$astroData['rid1'] || !in_array($astroData['astro_type'], [1, 2], false))
                {
                    return show(config('code.error'), '请求异常，请稍后再试～');
                }

                $recodeInfo1 = (new ZyhsRecode())->getInfoById($astroData['rid1']);
                if (!$recodeInfo1 || $recodeInfo1['uid'] != $this->user['id'])
                {
                    return show(config('code.error'), '请求异常！档案信息不存在～');
                }
                $questionExtend['recode1'] = [
                    'id' => (int)$astroData['rid1'],
                    'avatar' => $recodeInfo1['avatar'],
                    "name" => $recodeInfo1['name'],
                    "type" => (int)$recodeInfo1['type'],
                    "year" => (int)$recodeInfo1['year'],
                    "month" => (int)$recodeInfo1['month'],
                    "day" => (int)$recodeInfo1['day'],
                    "hour" => (int)$recodeInfo1['hour'],
                    "minute" => (int)$recodeInfo1['minute'],
                    "timezone" => (int)$recodeInfo1['timezone'],
                    "long_deg" => (int)$recodeInfo1['long_deg'],
                    "long_min" => (int)$recodeInfo1['long_min'],
                    "ew" => (int)$recodeInfo1['ew'],
                    "lat_deg" => (int)$recodeInfo1['lat_deg'],
                    "lat_min" => (int)$recodeInfo1['lat_min'],
                    "ns" => (int)$recodeInfo1['ns'],
                    "is_summer" => (int)$recodeInfo1['is_summer'],
                    "birth_country" => $recodeInfo1['birth_country'],
                    "birth_province" => $recodeInfo1['birth_province'],
                    "birth_city" => $recodeInfo1['birth_city'],
                    "live_country" => $recodeInfo1['live_country'],
                    "live_province" => $recodeInfo1['live_province'],
                    "live_city" => $recodeInfo1['live_city'],
                    "isself" => (int)$recodeInfo1['isself'],
                ];

                if ($astroData['astro_type'] == 2)
                {
                    $recodeInfo2 = (new ZyhsRecode())->getInfoById($astroData['rid2']);
                    if (!$recodeInfo2 || $recodeInfo2['uid'] != $this->user['id'])
                    {
                        return show(config('code.error'), '请求异常！档案信息不存在～');
                    }
                    $questionExtend['recode2'] = [
                        'id' => (int)$astroData['rid2'],
                        'avatar' => $recodeInfo2['avatar'],
                        "name" => $recodeInfo2['name'],
                        "type" => (int)$recodeInfo2['type'],
                        "year" => (int)$recodeInfo2['year'],
                        "month" => (int)$recodeInfo2['month'],
                        "day" => (int)$recodeInfo2['day'],
                        "hour" => (int)$recodeInfo2['hour'],
                        "minute" => (int)$recodeInfo2['minute'],
                        "timezone" => (int)$recodeInfo2['timezone'],
                        "long_deg" => (int)$recodeInfo2['long_deg'],
                        "long_min" => (int)$recodeInfo2['long_min'],
                        "ew" => (int)$recodeInfo2['ew'],
                        "lat_deg" => (int)$recodeInfo2['lat_deg'],
                        "lat_min" => (int)$recodeInfo2['lat_min'],
                        "ns" => (int)$recodeInfo2['ns'],
                        "is_summer" => (int)$recodeInfo2['is_summer'],
                        "birth_country" => $recodeInfo2['birth_country'],
                        "birth_province" => $recodeInfo2['birth_province'],
                        "birth_city" => $recodeInfo2['birth_city'],
                        "live_country" => $recodeInfo2['live_country'],
                        "live_province" => $recodeInfo2['live_province'],
                        "live_city" => $recodeInfo2['live_city'],
                        "isself" => (int)$recodeInfo2['isself'],
                    ];
                    $isSynastry = 1;
                }
                break;
            case 2: // 骰子
                $diceData = $diceData ? json_decode($diceData, true) : [];
                if (!$diceData || !isset($diceData['planet'], $diceData['sign'], $diceData['house']))
                {
                    return show(config('code.error'), '咨询骰子数据异常！');
                }
                $questionExtend['dice_data'] = $diceData;
                break;
            case 3: // 塔罗
                $tarotData = $tarotData ? json_decode($tarotData, true) : [];
                if (!$tarotData || count($tarotData) !== 3)
                {
                    return show(config('code.error'), '咨询塔罗数据异常！');
                }
                foreach ($tarotData as $item)
                {
                    if (!isset($item['img'], $item['tips'], $item['name']))
                    {
                        return show(config('code.error'), '咨询塔罗数据异常！');
                    }
                }
                $questionExtend['tarot_data'] = $tarotData;
                break;
            default:
        }

        $questionData['is_synastry'] = $isSynastry; // 是否合盘
        $questionData['question_extend'] = json_encode($questionExtend, JSON_UNESCAPED_UNICODE);

        try
        {
            $qidHash = uniqid('zyhs');
            $questionStr = json_encode($questionData, JSON_UNESCAPED_UNICODE);
            // 存储临时数据
            (new ZyhsUserQuestion())->setTmpQuestionDataCache($qidHash, $questionStr);

            return show(config('code.success'), '发布成功', ['qid' => $qidHash]);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 追问
     */
    public function addQuestion()
    {
        $taskId = input('task_id/s', '');
        $content = trim(input('content/s', ''));
        if (!$taskId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (!$content)
        {
            return show(config('code.error'), '请输入追问问题');
        }
        if (mb_strlen($content) > 50)
        {
            return show(config('code.error'), '追问问题最多50字');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'zyhsAddQuestion', 'taskId' => $taskId, 'content' => $content,], 5))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }
        $res = AliyunFilterWord::checkText($content, 'article_comment');
        //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
            return [
                'status' => false,
                'msg' => '内容中有敏感词',
            ];
        }

        $zyhsAstrTasksModel = new ZyhsAstrTasks();
        $zyhsUserQuestionModel = new ZyhsUserQuestion();
        $zyhsUserAddQuestionModel = new ZyhsUserAddQuestion();

        $astrTaskInfo = $zyhsAstrTasksModel->getInfoById($taskId, ['uid', 'status', 'qid', 'astr_id']);
        if (!$astrTaskInfo || $astrTaskInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，问题不存在～');
        }
        if ($astrTaskInfo['status'] !== 3)
        {
            return show(config('code.error'), '问答状态异常，请稍后再试～');
        }
        $questionInfo = $zyhsUserQuestionModel->getInfoById($astrTaskInfo['qid'], ['gid']);
        $gid = $questionInfo['gid'];
        $questionAnswerConfig = config('zyhs_question.info');
        $goodsInfo = $questionAnswerConfig[$gid];

        $addQuestionNum = $zyhsUserAddQuestionModel->getQuestionAddQuestionNum($taskId, 1);
        try
        {
            if ($goodsInfo['free_add_num'] > $addQuestionNum)
            {   // 免费追问
                $addQuestionId = $zyhsUserAddQuestionModel->SaveData($taskId, [
                    'task_id' => $taskId,
                    'activity_discount' => 1,
                    'uid' => $this->user['id'],
                    'status' => 2,
                    'question' => $content,
                    'create_time' => $this->request->time(),
                    'pay_time' => $this->request->time(),
                ]);
                // 问题状态更新至 追问待解答
                $zyhsAstrTasksModel->UpdateData($taskId, $astrTaskInfo['astr_id'], ['status' => 5, 'update_time' => $this->request->time()]);
                // 发送短信
                $hour = (int)(date('H'));
                if ($hour >= 10 && $hour < 20)
                {   // 白天
                    $msgContent = "你的任务{$taskId}有新的追问，请在3小时内给出回复，超时将受到惩罚。";
                    $timeStr = '3小时内给出';
                } else
                {   // 晚上
                    $timeStr = $hour >= 20 ? '次日11点前' : '11点前';
                    $msgContent = "你的任务{$taskId}有新的追问，请在{$timeStr}回复，超时将受到惩罚。";
                }

                $tel = (new ZlcrAstr())->getInfoById($astrTaskInfo['astr_id'], ['tel']);
                // 发送短信 通知咨询师
                Util::sendHySms([$tel['tel']], '', 131493, ['task_id' => $taskId, 'time' => $timeStr]);
                // 发送占星师站内信
                (new ZlcrAstrMessage())->add($astrTaskInfo['astr_id'], [
                    'status' => 0,
                    'is_read' => 0,
                    'astr_id' => $astrTaskInfo['astr_id'],
                    'type' => 0, // 占星师违规消息
                    'title' => '追问提示',
                    'content' => $msgContent,
                    'target' => 'local',
                    'link' => '/quiz/answer?task_id=' . $taskId . '&app_type=2',
                    'create_time' => $this->request->time(),
                ]);

                // if ($hour >= 10 && $hour < 20)    不发送
                // {   // 白天   追问1小时是否回复检测 未回复发送消息提醒
                //     Util::queuePush('zyhs_question_answer_add_question_reply_notify_check', ['add_question_id' => $addQuestionId, 'astr_id' => $astrTaskInfo['astr_id']], 3600);
                // }
                // 追问回复超时 检测
                Util::queuePush('zyhs_question_answer_add_question_reply_timeout_check', ['add_question_id' => $addQuestionId], Util::getZyhsToAnswerTime($this->request->time()));

                return show(config('code.success'), '追问成功', ['status' => 1]);
            } else
            {   // 付费追问
                $zyhsUserAddQuestionModel->setTmpAddQuestionData($taskId, ['content' => $content]);

                return show(config('code.success'), '提交成功', ['status' => 2]);
            }
        }
        catch (\Exception $e)
        {
            Log::write('准有好事 - 问答 QuestionAnswer => addQuestion()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
